const express = require('express');
const router = express.Router();
const createError = require('http-errors');
const User = require('../models/User');

// 获取用户信息接口
router.get('/info', async (req, res, next) => {
  try {
    // 从 auth 中间件获取用户 id
    const { id } = req.user;

    // 查询用户信息
    const user = await User.findOne({
      where: { id },
      attributes: [
        'id',
        'nickname',
        'gender',
        'avatar',
        'age',
        'openid',
        'warningNum',
        'createdAt',
        'updatedAt'
      ]
    });

    if (!user) {
      throw createError(404, '用户不存在');
    }

    res.json(user);

  } catch (error) {
    next(error);
  }
});

// 修改用户警告次数
router.put('/warning', async (req, res, next) => {
  try {
    const { id } = req.user;
    const { warningNum } = req.body;

    // 参数验证
    if (typeof warningNum !== 'number') {
      throw createError(400, 'warningNum必须是数字类型');
    }

    // 查找并更新用户
    const user = await User.findOne({ where: { id } });

    if (!user) {
      throw createError(404, '用户不存在');
    }

    // 更新warningNum
    await user.update({ warningNum });

    // 返回更新后的用户信息
    res.json({
      id: user.id,
      warningNum: user.warningNum,
      updatedAt: user.updatedAt
    });

  } catch (error) {
    next(error);
  }
});

module.exports = router;
